package com.example.dollarShipping.controller.carrier;

import com.alibaba.fastjson.JSON;
import com.example.dollarShipping.entity.*;
import com.example.dollarShipping.security.UserDetailsImpl;
import com.example.dollarShipping.service.CarrierService;
import com.example.dollarShipping.service.MenuService;
import com.example.dollarShipping.service.UserService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/carrier")
public class CarrierController {

    @Resource
    CarrierService carrierService;
    @Resource
    UserService userService;
    @Resource
    private MenuService menuService;

    @Resource
    PasswordEncoder passwordEncoder;

    @ModelAttribute("carrier")
    public Carrier carrierDto() {
        //获得spring security用户
        UserDetailsImpl userDetails = (UserDetailsImpl) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        User u = userService.getDetail(userDetails.getId());
        Carrier c = carrierService.findCarrier(u.getCarrier().getId());
        return c;
    }

    @ModelAttribute("menuList")
    public List<Menu> backGround() {
        UserDetailsImpl userDetails = (UserDetailsImpl) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        List<Menu>  menu= menuService.getMenu(userDetails.getRoleId());
        return menu;
    }

    @RequestMapping("/info")
    public String showProfileForm(Model model) {
        //获得spring security用户

        model.addAttribute("c",1);
        return "carrier/carrierInfo";
    }

    @RequestMapping("/update")
    public String update() {
        System.out.println("update");
        return "carrier/carrierUpdate";
    }

    @RequestMapping("/takeOrder")
    public String showTakeOrderPage(Model model) {
        UserDetailsImpl userDetails = (UserDetailsImpl) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        User u = userService.getDetail(userDetails.getId());
        Carrier c = carrierService.findCarrier(u.getCarrier().getId());
        List<ShippingOrder> sl = carrierService.getShippingOrder(1,null);
        model.addAttribute("shippingOrderList",sl);
        model.addAttribute("userId",userDetails.getId());
        model.addAttribute("carrierId",c.getId());
        System.out.println("takeOrder");
        return "carrier/takeOrder";
    }

    @RequestMapping("/myShippingOrder")
    public String showShippingOrderList(Model model) {
        UserDetailsImpl userDetails = (UserDetailsImpl) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        User u = userService.getDetail(userDetails.getId());
        List<ShippingOrder> sl = carrierService.getShippingOrder(2,u.getCarrier().getId());
        model.addAttribute("shippingOrderList",sl);
        model.addAttribute("userId",userDetails.getId());
        System.out.println("getShippingOrderList");
        return "carrier/myShippingList";
    }

    @GetMapping("/assignTruck{orderId}")
    public String showAssignTruck(Model model, @PathVariable(name="orderId") Long orderId) {
        UserDetailsImpl userDetails = (UserDetailsImpl) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        User u = userService.getDetail(userDetails.getId());
        List<User> drivers = carrierService.findFreeDrivers(u.getCarrier().getId());
        List<Truck> trucks = carrierService.findFreeTrucks(u.getCarrier().getId());
        ShippingOrder s =carrierService.findShippingOrder(orderId);
        model.addAttribute("driver",JSON.toJSONString(drivers));
        model.addAttribute("truck",JSON.toJSONString(trucks));
        model.addAttribute("userId",userDetails.getId());
        model.addAttribute("carrierId",u.getCarrier().getId());
        model.addAttribute("shippingOrder",s);
        System.out.println("assignTruck");
        return "carrier/assignTruckOrder";
    }

    //货运单详情
    @GetMapping("detail{orderId}")
    public String getCarrierList(Model model, @PathVariable(name="orderId") Long orderId){
        ShippingOrder s = carrierService.findShippingOrder(orderId);
        model.addAttribute("shippingOrder",s);
        return "detailShippingOrder";
    }

    @PostMapping("/addDriver")
    public String addDriver(@RequestParam Map<String, Object> params){
        System.out.println("addDriver");
        Integer roleId = Integer.parseInt(params.get("roleId").toString());
        Long carrierId = Long.parseLong(params.get("carrierId").toString());
        String userName = (String) params.get("userName");
        String realName = (String) params.get("realName");
        String password = (String) params.get("password");
        password = passwordEncoder.encode(password);
        String phone = (String) params.get("phone");
        String email = (String) params.get("email");
        try {
            userService.addDriver(carrierId,userName,realName,password,roleId,phone,email);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "carrier/carrierUpdate";
    }

    @PostMapping("/addTruck")
    public String addTruck(@RequestParam Map<String, Object> params){
        System.out.println("addTruck");
        Long carrierId = Long.parseLong(params.get("carrierId").toString());
        String number = (String) params.get("number");
        Float weight = Float.parseFloat(params.get("weight").toString());
        String info = (String) params.get("info");
        try {
            carrierService.addTruck(carrierId,number,weight,info);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "carrier/carrierUpdate";
    }
    @PostMapping("/updateCarrier")
    public String addTruck(@ModelAttribute("carrier") Carrier c,
                           BindingResult result ){
        System.out.println("updateCarrier");
        try {
            carrierService.update(c);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "carrier/carrierInfo";
    }

    // 货运单签收/结算操作
    // 修改货运单状态并添加任务记录
    @PostMapping("/carrierOperate")
    public String carrierOperate(@RequestParam Map<String,Object> params){
        System.out.println("carrierOperate");
        Long carrierId = Long.parseLong(params.get("carrierId").toString());
        Long orderId = Long.parseLong(params.get("orderId").toString());
        Long operator = Long.parseLong(params.get("operator").toString());
        try {
            carrierService.changeState(carrierId, orderId, operator);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "driver/driverTruckOrder";
    }

    //创建派车单
    @PostMapping("createTruckOrder")
    public String createTruckOrder(@RequestParam Map<String, Object> params){
        Long orderId = Long.parseLong(params.get("orderId").toString());
        Long carrierId = Long.parseLong(params.get("carrierId").toString());
        Long driverId = Long.parseLong(params.get("driver").toString());
        Long truckId = Long.parseLong(params.get("truck").toString());
        String goods = (String) params.get("goods");
        Float weight = Float.parseFloat(params.get("weight").toString());
        try {
            carrierService.createTruckOrder(orderId,carrierId,driverId,truckId,goods,weight);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "driver/driverTruckOrder";
    }

}
